const path = require('path')

const multer = require('koa-multer')
const Jimp = require('jimp')
const { resAvatarPath, resPicturePath } = require('@/constants/file-path')

const avatarStorage = multer.diskStorage({
  destination: async (req, file, cb) => {
    cb(null, resAvatarPath())
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname))
  },
})
const avatarUpload = multer({
  // dest: resAvatarPath(),
  storage: avatarStorage,
})
const avatarHandler = avatarUpload.single('avatar')

const pictureStorage = multer.diskStorage({
  destination: async (req, file, cb) => {
    cb(null, resPicturePath())
  },
  // filename: (req, file, cb) => {
  //   cb(null, Date.now() + path.extname(file.originalname))
  // },
})
const pictureUpload = multer({
  // dest: resPicturePath(),
  storage: pictureStorage,
})
const pictureHandler = pictureUpload.array('picture', 9)

const pictureResize = async (ctx, next) => {
  try {
    // 1.获取所有的图像信息
    const files = ctx.req.files

    // 2.对图像进行处理(sharp/jimp)
    for (let file of files) {
      const destPath = path.join(file.destination, file.filename)

      Jimp.read(file.path).then((image) => {
        // image.resize(800, Jimp.AUTO).write(`${destPath}-large`)
        // image.resize(640, Jimp.AUTO).write(`${destPath}-middle`)
        image.resize(320, Jimp.AUTO).write(`${destPath}-small`)
      })
    }

    await next()
  } catch (error) {
    console.log(error)
  }
}

module.exports = {
  avatarUpload,
  avatarHandler,
  pictureHandler,
  pictureResize,
}
